package com.sxsihe.heartmate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.View;
import android.view.Window;
import android.widget.*;

import cn.pedant.SweetAlert.widget.SweetAlertDialog;
import com.neurosky.ecg.TGLibECG;
import com.sxsihe.heartmate.util.SharePreferenceUtil;
import com.sxsihe.heartmate.util.Transform;
import com.sxsihe.heartmate.util.UploadTask;
import com.sxsihe.heartmate.view.DrawWaveView;
import org.w3c.dom.Text;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
import cn.pedant.SweetAlert.widget.SweetAlertDialog;


public class PlaybackActivity extends Activity {

    boolean isDraw = false;
    boolean restart = true;
    boolean readFile  = false;
    String heartrate="", heart_age="", heart_count="", r2r="", mood="", stress="", signal="", status="", duration="", type="";
    int rateMin,rateMax;
    SharePreferenceUtil spu;


    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }


    public static String readLastLine(File file, String charset) throws IOException {
        if (!file.exists() || file.isDirectory() || !file.canRead()) {
            return null;
        }
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            long len = raf.length();
            if (len == 0L) {
                return "";
            } else {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    if (raf.readByte() == '\n') {
                        break;
                    }
                }
                if (pos == 0) {
                    raf.seek(0);
                }
                byte[] bytes = new byte[(int) (len - pos)];
                raf.read(bytes);
                if (charset == null) {
                    return new String(bytes);
                } else {
                    return new String(bytes, charset);
                }
            }
        } catch (FileNotFoundException e) {
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception e2) {
                }
            }
        }
        return null;
    }



    private DrawWaveView mWaveView = null;
    boolean mRunning = false;
    TextView mTvHeartRate;
    TextView hrvvalue,result_btn;
    Button draw_btn,xjfh_btn;
    String fullPath;
    ImageView back_icon;
    EcgReader mReader = new EcgReader();
    RandomAccessFile raf = null;
    File file = null;
    int lineIndex = 0;
    String tmp;
    long fileLength = 0;
    public static String TIME_FORMAT = "HH:mm:ss";

    public static String convert2String(long time,String format) {
            SimpleDateFormat sf = new SimpleDateFormat(format);
            Date date = new Date(time);
            return sf.format(date);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                try {
                    if (fileLength == 0L) {
                        return;
                    } else {

                        String line = "";
                        line = raf.readLine();

                        if (line != null) {
                            String value[] = line.split("\\|");
                            if (isInteger(value[1])) {
                               tmp = convert2String(Long.parseLong(value[0]),TIME_FORMAT);
                               updateWaveView(tmp,Integer.parseInt(value[1]));
                            }

                            if(!value[2].trim().equals("")){
                                if(Integer.parseInt(value[2])<rateMin||Integer.parseInt(value[2])>rateMax){
                                    mTvHeartRate.setTextColor(Color.RED);
                                }else{
                                    mTvHeartRate.setTextColor(Color.parseColor("#9A9A9A"));
                                }
                            }
                            mTvHeartRate.setText(value[2]);
                            restart = false;
                        }else{
                            isDraw=false;
                            restart = true;
                            draw_btn.setText("开始回放");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private Timer timer = new Timer(true);

    //任务
    private TimerTask task = new TimerTask() {
        public void run() {
            if (isDraw) {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        }
    };

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.playback2);
        if (spu == null) {
            spu = SharePreferenceUtil.getInstance(this);
        }
        rateMin = Integer.parseInt(spu.get("rateMin", "60"));
        rateMax = Integer.parseInt(spu.get("rateMax", "100"));
        mWaveView = (DrawWaveView) findViewById(R.id.curveView);
        mTvHeartRate = (TextView) findViewById(R.id.heartratevalue);
//        hrvvalue = (TextView) findViewById(R.id.hrvvalue);
        mWaveView.setValue(1550, 8000, -8000);
        mWaveView.updateDensity();

        timer.schedule(task, 1, 2);

        draw_btn = (Button) findViewById(R.id.draw_btn);
        draw_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDraw) {
                    draw_btn.setText("开始回放");
                    isDraw = false;
                } else {
                    draw_btn.setText("停止回放");
                    file = new File(fullPath);
                    try {
                        String statusLine = readLastLine(file, null);
                        readFile = true;
                        String[] arr = statusLine.split("\\|");
                        for (String str : arr) {
                            if (str.contains("averHeartRate")) {
                                heartrate = str.split(":")[1];
                            } else if (str.contains("heart_age")) {
                                heart_age = str.split(":")[1];
                            } else if (str.contains("heart_count")) {
                                heart_count = str.split(":")[1];
                            } else if (str.contains("r2r")) {
                                r2r = str.split(":")[1];
                            } else if (str.contains("mood")) {
                                mood = str.split(":")[1];
                            } else if (str.contains("stress")) {
                                stress = str.split(":")[1];
                            } else if (str.contains("signal")) {
                                signal = str.split(":")[1];
                            } else if (str.contains("status")) {
                                status = str.split(":")[1];
                            } else if (str.contains("duration")) {
                                duration = str.split(":")[1];
                            } else if (str.contains("type")) {
                                type = str.split(":")[1];
                            }
                        }
//                        if(Integer.parseInt(heartrate)<rateMin||Integer.parseInt(heartrate)>rateMax){
//                            mTvHeartRate.setTextColor(Color.RED);
//                        }else{
//                            mTvHeartRate.setTextColor(Color.parseColor("#9A9A9A"));
//                        }
                        mTvHeartRate.setText("");
                        raf = new RandomAccessFile(file, "r");
                        fileLength = raf.length();
                        isDraw = true;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (!file.exists() || file.isDirectory() || !file.canRead()) {
                        return;
                    }
                }
            }
        });

        xjfh_btn = (Button)findViewById(R.id.xjfh_btn);
        xjfh_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                System.out.println(fullPath);
                Transform t = new Transform();
                try {
                    String filepath =  t.transFile(getIntent().getStringExtra("filename").replace(".data",""));
                    if(filepath==null) throw new Exception("没有数据文件");
                    new UploadTask().execute(filepath,"http://101.132.157.29:8010/sendfile?addr=xxx&pwd=xxx");
                } catch (Exception e) {
                    new SweetAlertDialog(PlaybackActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("出错了")
                            .setContentText("找不到对应的数据文件")
                            .show();
                    e.printStackTrace();
                }
            }
        });

        back_icon = (ImageView) findViewById(R.id.back_icon);
        back_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlaybackActivity.this.finish();
            }
        });

//        result_btn = (TextView)findViewById(R.id.result_btn);
//        result_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(!readFile) return;
//                if (isDraw) {
//                    draw_btn.performClick();
//                }
//                Intent intent = new Intent(PlaybackActivity.this, DiagnoseActiviy2.class);
//                intent.putExtra("heart_age", heart_age + "");
//                intent.putExtra("heart_count", heart_count + "");
//                intent.putExtra("r2r", r2r + "");
//                intent.putExtra("mood", mood + "");
//                intent.putExtra("stress", stress);
//                intent.putExtra("heartrate", heartrate + "");
//                intent.putExtra("signal", Integer.parseInt(signal)/2+"%");
//                intent.putExtra("duration", duration);
//                intent.putExtra("type", type);
//                startActivity(intent);
//                finish();
//            }
//        });

        Intent intent = getIntent();
        fullPath = getFilesDir().getPath() + "/" + intent.getStringExtra("filename");
    }

    public void updateWaveView(String  str,int data) {
        if (mWaveView != null) {
            int d = (int) (data *1.5);
            if(restart) {
                mWaveView.clear();
            }
            mWaveView.updateData(str,d);
        }
    }
}
